using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using netcore_comm.JWT;
using netcore_comm.Middleware;
using NLog.Web;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Polly;
using Panda.DynamicWebApi;
using Swashbuckle.AspNetCore.Filters;
using System.Text;


var builder = WebApplication.CreateBuilder(args);
IConfigurationRoot configuration = builder.Configuration;
// Add services to the container.

builder.Host.UseNLog();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMvc(option =>
{
    option.EnableEndpointRouting = false;
    //option.Filters.Add(new AuthorizeFilter());
});
builder.Services.AddDynamicWebApi(new DynamicWebApiOptions
{
    DefaultApiPrefix = "wechatappletapi"
});
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
    c.DocInclusionPredicate((docName, description) => true);
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.ApiKey,
        Name = "Authorization",
        In = ParameterLocation.Header
    });
    c.OperationFilter<SecurityRequirementsOperationFilter>();
    c.OperationFilter<AddResponseHeadersFilter>();
    c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
});


#region jwtУ��  HS
JWTTokenOptions tokenOptions = new JWTTokenOptions();
configuration.Bind("JWTTokenOptions", tokenOptions);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        //JWT��һЩĬ�ϵ����ԣ����Ǹ���Ȩʱ�Ϳ���ɸѡ��
        ValidateIssuer = true,//�Ƿ���֤Issuer
        ValidateAudience = true,//�Ƿ���֤Audience
        ValidateLifetime = true,//�Ƿ���֤ʧЧʱ��
        ValidateIssuerSigningKey = true,//�Ƿ���֤SecurityKey
        ValidAudience = tokenOptions.Audience,//
        ValidIssuer = tokenOptions.Issuer,//Issuer���������ǰ��ǩ��jwt������һ��
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),//�õ�SecurityKey
    };
});
#endregion
builder.Services.Configure<JWTTokenOptions>(configuration.GetSection("JWTTokenOptions"));

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 1024 * 1024 * 500; // 500MB
});

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 1048576L * 500L; //500MB
});

//Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(container =>
{
    container.RegisterModule(new netcore_service.ServiceRegistration());
});

builder.Services.AddSignalR();

builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "netcore_api",
                      builder =>
                      {
                          builder
.WithOrigins("http://0.0.0.0:8080", "http://localhost:8080")//֧�ֶ�������˿ڣ�ע��˿ںź�Ҫ��/б�ˣ�����localhost:8000/���Ǵ��� 
.AllowAnyHeader()//Ensures that the policy allows any header.
.AllowAnyMethod()
.AllowCredentials();
                      });
});

//builder.Services.AddBrowserService();
var app = builder.Build();

// 上传最大文件限制

//app.UseBrowser();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
else
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "api v1"));
}
app.UseCors("netcore_api");

// string path = "/app/wwwroot/Logo";
// if (!Directory.Exists(path))
// {
//     Directory.CreateDirectory(path);
// }
if (app.Environment.WebRootPath == null)
{
    app.Environment.WebRootPath = Path.Combine(app.Environment.ContentRootPath, "wwwroot");
    Directory.CreateDirectory(app.Environment.WebRootPath);
}
string webRootPath = Path.Combine(app.Environment.WebRootPath, "Logo");
if (!Directory.Exists(webRootPath))
{
    Directory.CreateDirectory(webRootPath);
}
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(webRootPath),
    RequestPath = "/Logo"
});
app.UseRouting();
app.Use((context, next) =>
{
    if (context.Request.Query.TryGetValue("Bearer", out var token))
        context.Request.Headers.Add("Authorization", $"Bearer {token}");
    return next.Invoke();
});
app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();
app.MapHub<ChatHub>("/wechatappletapi/chatHub");

app.Run();


